#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{

  pid_t id = fork();
  if(id < 0)
  {
    perror("fork");
    return 1;
  }
  else if(id == 0)
  {
    //child 
    int cnt = 3;
    while(cnt)
    {
      //int a = 10;
      //int ret = a / 0;
      printf("I am child, pid : %d, ppid : %d, cnt = %d\n", getpid(), getppid(), cnt);
      --cnt;
      sleep(1);
    }
    exit(0);
  }
  else
  {
    int cnt = 5;
    while(cnt)
    {

      printf("I am parent, pid : %d, ppid : %d, cnt = %d\n", getpid(), getppid(), cnt);
      --cnt;
      sleep(1);
    }
  }
  //wait
  //pid_t ret = wait(NULL);
  //waitpid() 
  int status = 0; 
  pid_t ret = waitpid(id, &status, WNOHANG);
  while(1)
  {
    if(ret > 0)
    {
      //printf("wait success\n");
      if(WIFEXITED(status))
      {
        printf("normal exit, exitcode: %d\n", WEXITSTATUS(status));
        sleep(1);
      }
      else
      {
        printf("proc exception\n");
        sleep(1);
      }
    }
    else if(ret == 0)
    {
      printf("child don't stop, wait\n"); 
      sleep(1);
    } 
    else 
    {
      printf("wait fail\n");
      sleep(1);
    }
  }

  return 0;
}
